package com.常用类.Arrays数组类;

import java.util.Comparator;

/**
 * 编写Book类，创建四个对象，按照Price大小来定制排序；
 */
@SuppressWarnings("all")
public class Exercise01 {
    public static void main(String[] args) {
        Book a[] = new Book[4];
        a[0] = new Book("红楼梦", 100);
        a[1] = new Book("金瓶梅", 90);
        a[2] = new Book("青年文摘", 5);
        a[3] = new Book("Java", 300);

        MySort(a, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                int b1 = (Integer) o1;
                int b2 = (Integer) o2;
                return b1 - b2;//升序，
                // if (c.compare(a[j].price , a[j + 1].price) > 0) 前面的大于后面的返回正数，执行交换，导致升序；
            }
        });


        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }

    }

    static void MySort(Book[] a, Comparator c) {
        Book temp;
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (c.compare(a[j].getPrice(), a[j + 1].getPrice()) > 0) {
                    temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
    }
}


class Book {
    private String name;
    private int price;

    public Book(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    public String getName() {
        return name;
    }

    public int getPrice() {
        return price;
    }
}
